// import { isAliPay } from '../validate'
import request from '@/utils/request'
import authority from '../authority'
import qs from './qs'

// 主动登陆地址
function getLoginUrl(customBack) {
  const baseUrl = 'https://koubei.halobear.com/api/store/alipay/authorization'
  let backUrl = customBack
  if (!backUrl) {
    const { origin, pathname, search } = window.location
    backUrl = encodeURIComponent(`${origin}${pathname}${search}`)
  }
  return `${baseUrl}?back=${backUrl}`
}

// 去除alipay_code
function refreshPage(url) {
  const { origin, pathname } = window.location
  const searchData = qs.parse(url || window.location.href)
  if (searchData.alipay_code) {
    delete searchData.alipay_code
    const href = url.split('?')[0] || `${origin}${pathname}`
    window.location.replace(`${href}?${qs.stringify(searchData)}`)
  }
}

// 保存用户信息
async function toLogin(backUrl) {
  const params = qs.parse(window.origin.href)
  const code = params.alipay_code

  if (code) {
    // 登陆返回code，获取用户信息
    const { token, user } = await request({
      url: '/api/store/authorization',
      method: 'post',
      data: {
        token: code
      }
    })
    authority.set({ token, user })
    refreshPage(backUrl)
  } else {
    // 直接登陆
    const loginUrl = getLoginUrl(backUrl)
    window.location.replace(loginUrl)
  }
  return true
}

// 登陆
export function login(backUrl) {
  // 已经登陆或者不是支付宝 直接return
  // if (authority.get() || !isAliPay) return
  if (authority.get()) return true
  // 保存用户信息
  return toLogin(backUrl)
}

// 401强制登陆
export function login401() {
  localStorage.clear()
  login()
}
